package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
@Slf4j
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            //1.解析协议内容
            SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            //2.找出被指派人
            VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());
            int userId = taskService.getLeastUser(vmInfo.getRegionId(), false);
            if(vmInfo==null||userId==0){
                return;
            }
            //3.创建补货工单
            TaskViewModel taskViewModel=new TaskViewModel();
            taskViewModel.setUserId(userId);
            taskViewModel.setCreateType(0);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setInnerCode(supplyContract.getInnerCode());
            taskViewModel.setAssignorId(0);
            taskViewModel.setDesc("自动补货工单");

            taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(d->{
                TaskDetailsViewModel taskDetailsViewModel=new TaskDetailsViewModel();
                taskDetailsViewModel.setChannelCode(d.getChannelId());
                taskDetailsViewModel.setExpectCapacity(d.getCapacity());
                taskDetailsViewModel.setSkuId(d.getSkuId());
                taskDetailsViewModel.setSkuName(d.getSkuName());
                taskDetailsViewModel.setSkuImage(d.getSkuImage());
                return taskDetailsViewModel;
            }).collect(Collectors.toList()));
            taskService.addTask(taskViewModel);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("自动创建补货工单出错"+e.getMessage());
        }

    }
}
